<?php

namespace app\admin\controller;

use app\admin\model\SalesDetail;
use app\admin\model\SystemUploadfile;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\tool\CommonTool;
use jianyan\excel\Excel;
use think\App;
use think\facade\Db;

/**
 * Class Admin
 * @package app\admin\controller
 * @ControllerAnnotation(title="销售记录管理")
 */
class Sales extends AdminController
{

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Sales();
        
        $this->assign('getTypeList', $this->model->getTypeList());

        $this->assign('getProjectStatusList', $this->model->getProjectStatusList());

        $this->assign('getStatusList', $this->model->getStatusList());

    }

    /**
     * @NodeAnotation(title="对接中")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFieds')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            // 强行不联表查询，进行where拦截
            foreach ($where as $k => $v){
                if ($v[0] == 'true_name'){
                    $where[$k] = whereHook($v, 'uid', '\app\admin\model\Users','uid');
                }
            }
            $where[] = ['status', '=', 0];
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            foreach ($list as $k => $v) {
                $list[$k]['true_name'] = \app\admin\model\Users::where('uid', $v['uid'])->value('true_name');
                $detail = SalesDetail::where('sales_id', $v['id'])->order('id', 'desc')->limit(1)->select();
                if ($detail->isEmpty()){
                    $list[$k]['is_today'] = 0;
                    $list[$k]['last_time'] = '无';
                }else{
                    $detail = $detail->toArray();
                    if (strtotime($detail[0]['create_time']) < strtotime(date('Y-m-d 0:0:0', time()))){
                        $list[$k]['is_today'] = 0;
                    }else{
                        $list[$k]['is_today'] = 1;
                    }
                    $list[$k]['last_time'] = $detail[0]['create_time'];
                }
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $sales['today'] = \app\admin\model\Sales::whereDay('create_time')->count();
        $today_num = 0;
        $res = \app\admin\model\Sales::whereTime('create_time','<', strtotime(date('Y-m-d'), time()))->select();
        foreach ($res as $k => $v){
            $today_num += SalesDetail::whereDay('create_time','today')->where('sales_id', $v['id'])->count();
        }
        $sales['success'] = $today_num ? round($today_num / count($res) * 100,2) : 0;
        $this->assign('sales', $sales);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="已失败")
     */
    public function index2()
    {
        if ($this->request->isAjax()) {
            if (input('selectFieds')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            // 强行不联表查询，进行where拦截
            foreach ($where as $k => $v){
                if ($v[0] == 'true_name'){
                    $where[$k] = whereHook($v, 'uid', '\app\admin\model\Users','uid');
                }
            }
            $where[] = ['status', '=', 1];
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            foreach ($list as $k => $v) {
                $list[$k]['true_name'] = \app\admin\model\Users::where('uid', $v['uid'])->value('true_name');
                $detail = SalesDetail::where('sales_id', $v['id'])->order('id', 'desc')->limit(1)->select();
                if ($detail->isEmpty()){
                    $list[$k]['is_today'] = 0;
                    $list[$k]['last_time'] = '无';
                }else{
                    $detail = $detail->toArray();
                    $list[$k]['last_time'] = $detail[0]['create_time'];
                    if (strtotime($detail[0]['create_time']) < strtotime(date('Y-m-d 0:0:0', time()))){
                        $list[$k]['is_today'] = 0;
                    }else{
                        $list[$k]['is_today'] = 1;
                    }
                }
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {
        list($page, $limit, $where) = $this->buildTableParames();
        $tableName = $this->model->getName();
        $tableName = CommonTool::humpToLine(lcfirst($tableName));
        $prefix = config('database.connections.mysql.prefix');
        $dbList = Db::query("show full columns from {$prefix}{$tableName}");
        $header = [];
        foreach ($dbList as $vo) {
            $comment = !empty($vo['Comment']) ? $vo['Comment'] : $vo['Field'];
            if (!in_array($vo['Field'], $this->noExportFileds)) {
                $header[] = [$comment, $vo['Field']];
            }
        }
        $list = $this->model
            ->where($where)
            ->limit(100000)
            ->order($this->sort)
            ->select()
            ->toArray();
        $fileName = time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }

    /**
     * @NodeAnotation(title="追销记录")
     */
    public function detail()
    {
        $id = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (empty($row)){
            return json([
                'code' => 0,
                'msg' => '',
                'count' => 0,
                'data' => '',
            ]);
        }
        if ($this->request->isAjax()) {
            $row = $row->images->visible(['url', 'create_time'])->toArray();
            $data = [
                'code' => 0,
                'msg' => '',
                'count' => count($row),
                'data' => $row,
            ];
            return json($data);
        }
        $row['true_name'] = \app\admin\model\Users::where('uid', $row->uid)->value('true_name');
        $row['type'] = $this->model->getTypeList()[$row['type']];
        $row['status'] = $this->model->getStatusList()[$row['status']];
        $row['project_status'] = $this->model->getProjectStatusList()[$row['project_status']];
        if ($row['img_ids']){
            $row['img_ids'] = explode(',', $row['img_ids']);
            $row['img_ids'] = SystemUploadfile::whereIn('id', $row['img_ids'])->column('url');
        }else{
            $row['img_ids'] = [];
        }
        $this->assign('row', $row);
        return $this->fetch();
    }
}